#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import socketserver
import logging
import subprocess

import yaml


def get_server_token():
    token = ''
    yamlfile = os.path.join("/Users/ddy", "svn.yaml")

    f = open(yamlfile, 'r', encoding='utf-8')
    content = f.read()
    # print(content)

    yamlObj = yaml.load(content)
    try:
        token = yamlObj['svn']['socket_test']['token']
    except KeyError as e:
        logging.error(e)
    finally:
        return token


class MyServer(socketserver.BaseRequestHandler):
    logging.basicConfig(level=logging.DEBUG,  # 控制台打印的日志级别
                        filename='/Users/ddy/python.log',
                        filemode='a',  # 模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志
                        # a是追加模式，默认如果不写的话，就是追加模式
                        format=
                        '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                        # 日志格式
                        )

    def handle(self):
        # print("got connection from", self.client_address)
        # while True:
        conn = self.request
        # print("waiting for token...")
        token = conn.recv(512)
        if not token:
            return
        try:
            token.decode()
        except UnicodeDecodeError as e:
            conn.send("error", e)
            conn.close()
        token_str = str(token, 'utf8').strip()
        logging.info("client:{}, token:{}".format(self.client_address, token_str))

        token_on_server = get_server_token()
        # print(token_on_server, token_str)
        # print(len(token_on_server), len(token_str))

        if token_on_server == token_str:
            cmd = conn.recv(1024)
            try:
                cmd.decode()
            except UnicodeDecodeError as e:
                conn.send("error", e)
                conn.close()
            logging.info("client:{}, cmd:{}".format(self.client_address, str(cmd, 'utf8')))
            result = subprocess.Popen(cmd.decode('utf-8').strip(), shell=True, stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            msg = result.stdout.read()
            if len(msg) == 0:
                msg = result.stderr.read()
            # print(msg)
            conn.send(msg)
            conn.close()
        else:
            logging.info("token error: " + token_str)
            conn.close()
            return


if __name__ == '__main__':
    server = socketserver.ThreadingTCPServer(('172.31.100.250', 8090), MyServer)
    server.serve_forever()
